package com.aiti.lulian.gxmh.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.lulian.constant.GxmhConstant;
import com.aiti.lulian.gxmh.dto.GxmhFormTypeDto;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.gxmh.entity.GxmhCustomizeFormType;
import com.aiti.lulian.gxmh.service.GxmhCustomizeFormTypeService;
import com.aiti.lulian.gxmh.vo.GxmhAbstractItemVo;
import com.aiti.lulian.gxmh.vo.GxmhCustomizeFormTypeVo;
import com.aiti.lulian.mapper.gxmh.GxmhCustomizeFormTypeMapper;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description:
 * auth fcb
 * date 2025-07-07 13:37
 **/
@Service
@Slf4j
public class GxmhCustomizeFormTypeServiceImpl extends BaseSerivceImpl<GxmhCustomizeFormTypeMapper, GxmhCustomizeFormType> implements GxmhCustomizeFormTypeService {

    @Autowired
    private GxmhSysMapper gxmhSysMapper;

    /**
     * 新增表单类型，如果一级类型已经存在，则尝试仅创建二级类型
     * 如果二级类型也存在，则返回已经存在的类型数据，
     * 如果类型都不存在则创建一二级类型
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public GxmhCustomizeFormTypeVo addFormType(GxmhFormTypeDto dto, String loginId) {
        if(StrUtil.isBlank(dto.getTypeOneName()) || StrUtil.isBlank(dto.getTypeTwoName())) {
            throw new BusinessException("表单类型不能为空");
        }
        if("系统默认".equals(dto.getTypeOneName())) {
            throw new BusinessException("请创建或选择其他表单类型");
        }
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        this.checkAdminParam(dto, sysUserDto.getUsername());
        // 非管理员设置当前账号的区域
        if(!GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            dto.setProvince(sysUserDto.getProvince());
            dto.setCity(sysUserDto.getCity());
            dto.setCounty(sysUserDto.getRegion());
            dto.setStreet(sysUserDto.getStreet());
        }
        GxmhCustomizeFormTypeVo typeVo = new GxmhCustomizeFormTypeVo();
        // 1. 一级类型存在
        GxmhCustomizeFormType oneLevelType = this.baseMapper.queryFormTypeByName(dto.getTypeOneName(), "0", dto.getProvince(), dto.getCity(), dto.getCounty());
        if(oneLevelType != null) {
            GxmhCustomizeFormType twoLevelType = this.baseMapper.queryFormTypeByName(dto.getTypeTwoName(), oneLevelType.getBaseId(),  dto.getProvince(), dto.getCity(), dto.getCounty());
            if(twoLevelType != null) {
                typeVo.setTypeOneId(oneLevelType.getBaseId());
                typeVo.setTypeOneName(oneLevelType.getFormTypeName());
                typeVo.setTypeTwoId(twoLevelType.getBaseId());
                typeVo.setTypeTwoName(twoLevelType.getFormTypeName());
                return typeVo;
            }else {
                twoLevelType = new GxmhCustomizeFormType();
                String typeTwoId = IdUtil.simpleUUID();
                twoLevelType.setBaseId(typeTwoId);
                twoLevelType.setFormTypeName(dto.getTypeTwoName());
                twoLevelType.setParentId(oneLevelType.getBaseId());
                twoLevelType.setBaseCreateBy(loginId);
                twoLevelType.setBaseUpdateBy(loginId);
                twoLevelType.setBaseCreateTime(new Date());
                twoLevelType.setBaseUpdateTime(new Date());
                twoLevelType.setIsDelete(0);
                twoLevelType.setProvince(dto.getProvince());
                twoLevelType.setCity(dto.getCity());
                twoLevelType.setCounty(dto.getCounty());
                twoLevelType.setStreet(dto.getStreet());
                this.save(twoLevelType);

                typeVo.setTypeOneId(oneLevelType.getBaseId());
                typeVo.setTypeOneName(oneLevelType.getFormTypeName());
                typeVo.setTypeTwoId(typeTwoId);
                typeVo.setTypeTwoName(dto.getTypeTwoName());
                return typeVo;
            }
        }
        // 2. 一级类型不存在，创建两个类型
        else {
            Date now = new Date();
            oneLevelType = new GxmhCustomizeFormType();
            String typeOneId = IdUtil.simpleUUID();
            oneLevelType.setBaseId(typeOneId);
            oneLevelType.setBaseCreateTime(now);
            oneLevelType.setBaseUpdateTime(now);
            oneLevelType.setFormTypeName(dto.getTypeOneName());
            oneLevelType.setParentId("0");
            oneLevelType.setIsDelete(0);
            oneLevelType.setBaseCreateBy(loginId);
            oneLevelType.setBaseUpdateBy(loginId);
            oneLevelType.setProvince(dto.getProvince());
            oneLevelType.setCity(dto.getCity());
            oneLevelType.setCounty(dto.getCounty());
            oneLevelType.setStreet(dto.getStreet());
            this.save(oneLevelType);

            GxmhCustomizeFormType twoLevelType = new GxmhCustomizeFormType();
            String typeTwoId = IdUtil.simpleUUID();
            twoLevelType.setBaseId(typeTwoId);
            twoLevelType.setFormTypeName(dto.getTypeTwoName());
            twoLevelType.setParentId(oneLevelType.getBaseId());
            twoLevelType.setIsDelete(0);
            twoLevelType.setBaseCreateBy(loginId);
            twoLevelType.setBaseUpdateBy(loginId);
            twoLevelType.setBaseUpdateTime(now);
            twoLevelType.setBaseCreateTime(now);
            twoLevelType.setProvince(dto.getProvince());
            twoLevelType.setCity(dto.getCity());
            twoLevelType.setCounty(dto.getCounty());
            twoLevelType.setStreet(dto.getStreet());

            this.save(twoLevelType);

            typeVo.setTypeOneName(oneLevelType.getFormTypeName());
            typeVo.setTypeOneId(oneLevelType.getBaseId());
            typeVo.setTypeTwoName(twoLevelType.getFormTypeName());
            typeVo.setTypeTwoId(twoLevelType.getBaseId());
            return typeVo;
        }
    }

    private void checkAdminParam(GxmhFormTypeDto dto, String username) {
        // 如果是管理员账号，则省市区县不能为空
        if(GxmhConstant.ADMIN_USER_NAME.equals(username)) {
            if(StrUtil.isBlank(dto.getProvince())) {
                throw new BusinessException("所属区域不能为空");
            }
            if(StrUtil.isBlank(dto.getCity())) {
                throw new BusinessException("所属区域不能为空");
            }
            if(StrUtil.isBlank(dto.getCounty())) {
                throw new BusinessException("所属区域不能为空");
            }
        }
    }

    /**
     * 返回表单类型或某类型下的表单
     * @param type  formType:表单类型，form：表单
     * @param loginId
     * @return
     */
    @Override
    public List<GxmhAbstractItemVo> getListByType(String type, String parentId, String loginId) {
        if(StrUtil.isBlank(parentId)) {
            parentId = "0";
        }
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        String province = sysUserDto.getProvince();
        String city = sysUserDto.getCity();
        String region = sysUserDto.getRegion();
        String street = sysUserDto.getStreet();
        // 管理员账号不设置区域
        if(GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            province = null;
            city = null;
            region = null;
        }
        if("formType".equals(type)) {
            return this.baseMapper.queryFormTypeList(parentId, province, city, region, street);
        }
        if("form".equals(type)) {
            return this.baseMapper.queryFormByTypeId(parentId);
        }
        return new ArrayList<>();
    }
}
